<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
      <el-form-item label="商品名称:" prop="queryGoodsName">
        <el-input v-model="queryParams.queryGoodsName" placeholder="根据商品名称搜索" clearable style="width: 200px"
          @keyup.enter="handleQuery" />
      </el-form-item>

      <el-form-item label="画师:" prop="queryUserId">
        <el-select :style="{ width: '100%' }" v-model="queryParams.queryUserId" filterable remote reserve-keyword
          placeholder="请输入画师昵称搜索画师" :remote-method="remoteMethod2" :loading="loadingGoods" clearable>
          <el-option v-for="item in optionsPainterList" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="商品类型:" prop="queryType">
        <el-select :style="{ width: '100px' }" v-model="queryParams.queryType" placeholder="请选择" clearable>
          <el-option v-for="item in typeList" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>


      <el-form-item label="开售日期:">
        <el-date-picker style="width: 220px" v-model="dateRange" value-format="YYYY-MM-DD" type="daterange"
          range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-hasPermi="['update']" type="primary" plain icon="Upload" @click="handleUpload">导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-hasPermi="['export']" type="primary" plain icon="Download" @click="handleExport">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-hasPermi="['pick']" type="primary" plain icon="Upload" @click="handleUploadPick">导入提货码</el-button>
      </el-col>

      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table v-loading="loading" :data="pageList" @selection-change="handleSelectionChange"
      @sort-change="handleSortChange">
      <el-table-column label="序号" align="center" type="index" width="100" />
      <el-table-column label="商品编号" align="center" prop="id" width="100" />
      <el-table-column label="图片" align="center" prop="src">
        <template #default="scope">
          <el-image v-if="scope.row.src" style="width: 50px; height: 50px" :src="uploadShowUrl + scope.row.src"
            :preview-teleported="true" :preview-src-list="[uploadShowUrl + scope.row.src]" :initial-index="0"
            fit="contain" />
          <div v-else style="width: 50px; height: 50px; line-height: 50px">
            未上传图片
          </div>
        </template>
      </el-table-column>
      <el-table-column label="商品名称" align="center" width="300" prop="name" :show-overflow-tooltip="true" />
      <el-table-column label="画师" align="center" prop="nickName" width="150" />
      <el-table-column label="开售日期" align="center" prop="saleTime" width="150" sortable>
        <template #default="scope">
          <span>{{ parseTime(scope.row.saleTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>

      <el-table-column label="商品类型" align="center" prop="type" width="150" :show-overflow-tooltip="true">
        <template #default="scope">
          <span>{{ handleChangeType(scope.row.type) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="价格" align="center" prop="price" width="100" sortable />
      <el-table-column label="库存总量" align="center" prop="saleSum" width="100" />
      <el-table-column label="转让状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="statusList" :value="scope.row.status" />
        </template>
      </el-table-column>

      <el-table-column label="适用范围" width="150" align="center" prop="useRange" :show-overflow-tooltip="true">
        <template #default="scope">
          <span>{{ handleChangeUseRange(scope.row.useRange) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建日期" align="center" prop="createdAt" width="150" sortable>
        <template #default="scope">
          <span>{{ parseTime(scope.row.createdAt, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>

      <el-table-column label="备注" align="center" prop="remarks" :show-overflow-tooltip="true" />
      <el-table-column label="提货码" align="center" prop="adminPickUp" width="150" :show-overflow-tooltip="true"
        v-hasPermi="['pick']" />
      <el-table-column label="店铺专用备注" align="center" prop="adminRemarks" width="150" v-hasPermi="['pick']"
        :show-overflow-tooltip="true" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="250" fixed="right">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" v-hasPermi="['good:edit']"
            @click="handleUpdate(scope.row)">修改</el-button>
          <el-button v-hasPermi="['del']" link type="primary" icon="Delete"
            @click="handleDelete(scope.row)">删除</el-button>
          <el-button v-hasPermi="['good:detail']" link type="primary" icon="Delete"
            @click="handleOpenSub(scope.row)">销量明细</el-button>
          <el-button v-hasPermi="['del']" link type="primary" icon="Delete"
            @click="handleShare(scope.row)">分享链接</el-button>

          <el-button v-hasPermi="['pick']" link type="primary" icon="Edit"
            @click="handleUpdatePick(scope.row)">提货码</el-button>

        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 新增和修改 共用 -->
    <el-dialog :title="title" v-model="open" width="780px" append-to-body>
      <el-form ref="noticeRef" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="商品名称:" prop="name">
              <el-input v-model="form.name" placeholder="请输入商品名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="画师:" prop="userId">
              <el-select v-model="form.userId" placeholder="请选择">
                <el-option v-for="dict in painterList" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开售日期:" prop="saleTime">
              <el-date-picker v-model="form.saleTime" type="date" placeholder="请输入开始售卖日期" format="YYYY/MM/DD"
                value-format="YYYY-MM-DD" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="价格:" prop="price">
              <el-input-number v-model="form.price" :min="0" :max="9999" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="库存数量:" prop="saleSum">
              <el-input-number v-model="form.saleSum" :min="0" :max="9999" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="适用范围:" prop="useRange">
              <el-radio-group v-model="form.useRange">
                <el-radio v-for="dict in useRangeList" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="商品类型:" prop="status">
              <el-radio-group v-model="form.type">
                <el-radio v-for="dict in typeList" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="是否可以转让:" prop="status" label-width="108px">
              <el-radio-group v-model="form.status">
                <el-radio v-for="dict in statusList" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>


          <el-col :span="24">
            <el-form-item label="图片上传" prop="path">
              <el-upload class="avatar-uploader" :action="uploadUrl" :show-file-list="false"
                :before-upload="beforeAvatarUpload" :http-request="handleFileUpload">
                <!-- :on-success="onSuccessImg" -->
                <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon">
                  <Plus />
                </el-icon>
              </el-upload>
            </el-form-item>
          </el-col>

        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="debouncedFn">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 新增和修改 共用 -->
    <el-dialog :title="title" v-model="openPick" width="780px" append-to-body>
      <el-form ref="goodsPickRef" :model="formPick" label-width="120px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="提货码" prop="pick_up">
              <el-input type="textarea" :rows="2" placeholder="请输入提货码" v-model="formPick.pick_up">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="店长专用备注" prop="remarks">
              <el-input type="textarea" :rows="2" placeholder="请输入店长专用备注" v-model="formPick.remarks">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="debouncedFnPick">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>



    <!-- 添加或修改框:title="detailTitle"  -->
    <el-dialog v-model="openSub" width="1200px" append-to-body>
      <template #title>
        <div class="detail-title">
          <div>{{ detailTitle }}</div>
          <div v-hasPermi="['money']">{{ detailTitle1 }}</div>
        </div>

      </template>

      <el-table v-loading="loadingSub" row-key="buyUserName" :data="pageListSub" max-height="800">
        <el-table-column label="序号" align="center" type="index" width="100" />
        <el-table-column label="订单编号" align="center" prop="id" width="150" />
        <el-table-column label="购买人qq号" align="center" prop="buyerQQ" width="150" />
        <el-table-column label="购买人昵称" align="center" prop="buyerQQNickName" width="150"
          :show-overflow-tooltip="true" />
        <el-table-column label="购买人店铺昵称" align="center" prop="buyerQQAliasNickName" width="150"
          :show-overflow-tooltip="true" />

        <el-table-column label="价格" align="center" prop="buyPrice" width="100" />
        <el-table-column label="平台" align="center" prop="platform" width="110" />
        <el-table-column label="售卖数量" align="center" prop="buySum" width="100" />
        <el-table-column label="购买日期" align="center" prop="buyDate" width="100">
          <template #default="scope">
            <span>{{ parseTime(scope.row.buyDate, "{y}-{m}-{d}") }}</span>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remarks" width="200" :show-overflow-tooltip="true" />

      </el-table>

    </el-dialog>

    <el-dialog title="分享链接" v-model="openShare" width="780px" append-to-body>
      <div>商品名称：{{ shareName }}</div>
      <div class="pt">
        分享地址：
        <section id="copy-text">
          {{ shareUrl }}
        </section>
      </div>
      <el-button type="primary" @click="handleCopy">复制链接</el-button>
    </el-dialog>


    <!-- 导入功能 -->
    <el-dialog :title="title" v-model="dialogOpen2" width="780px" append-to-body>
      <el-row>
        <el-col :span="24">
          <el-form-item label="模板下载">
            <el-button type="primary" @click="submitUploadFileDemo">下载xlsx模板</el-button>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="附件上传">
            <el-upload class="upload-demo" :action="uploadUrlFile" :file-list="fileList"
              :before-upload="beforeFileUpload" :on-success="onSuccessFile">
              <el-button type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">请按模板规范上传</div>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogCancel2">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 导入 提货码功能 -->
    <el-dialog :title="title" v-model="dialogOpenPick" width="780px" append-to-body>
      <el-row>
        <el-col :span="24">
          <el-form-item label="模板下载">
            <el-button type="primary" @click="submitUploadFileDemoPick">下载xlsx模板</el-button>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="附件上传">
            <el-upload class="upload-demo" :action="uploadUrlFilePick" :file-list="fileList"
              :before-upload="beforeFileUpload" :on-success="onSuccessFile">
              <el-button type="primary">点击上传提货码</el-button>
              <div slot="tip" class="el-upload__tip">请按模板规范上传</div>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogCancel2">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 导出 按钮 -->
    <el-dialog :title="title" v-model="dialogOpen1" width="780px" append-to-body>
      <el-form ref="orderRef1" :model="dialogForm1" label-width="120px">
        <el-row>
          <el-col :span="18">
            <el-form-item label="画师:" prop="userId">
              <el-select v-model="dialogForm1.userId" placeholder="请选择">
                <el-option v-for="dict in painterList" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="18">
            <el-form-item label="商品类型" prop="type">
              <el-select v-model="dialogForm1.type" clearable placeholder="请选择">
                <el-option v-for="item in typeList" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col>
            备注：选择对应的条件，如果不选则导出全部数据。
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitExport" :loading="loadingBtn">确 定</el-button>
          <el-button @click="dialogCancel1">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Goods">
import {
  listGoods,
  addGoods,
  updateGoods,
  deleteGoods,
  downExcelFile,
  downExcelGoods
} from "@/api/business/goods";


import {
  updateGoodsPick,
  getGoodsPickDetals,
  goodsPickDownExcelFile
} from "@/api/business/goodsPick";

import { listAllOrder } from "@/api/business/order";
import {
  listUser, listAllUser,
} from "@/api/business/user";
import { useDebounceFn } from "@vueuse/core";
import {
  h5UploadFile,

  getRandomString,
} from "@/components/upload/attachment.js";
import { goodsStutasEnums, yesOrNoEnums, goodsTypeEnums } from "@/utils/enums"

const { proxy } = getCurrentInstance();
// 图片上传地址
const uploadUrl = import.meta.env.VITE_APP_UPLOAD_API + "api/uploadFile/goods";
// 文件上传地址
const uploadUrlFile =
  import.meta.env.VITE_APP_UPLOAD_API + "api/uploadFileGoods/goods";
// 文件上传地址 -- 提货码
const uploadUrlFilePick =
  import.meta.env.VITE_APP_UPLOAD_API + "api/uploadFileGoodsPick/goodsPick";


const uploadShowUrl = import.meta.env.VITE_APP_COS_API;
const imageUrl = ref("");

const dateRange = ref([]);


const pageList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const openPick = ref(false);

const detailTitle = ref(""); // 详情标题栏
const detailTitle1 = ref(""); // 详情标题栏
const detaiRemarks = ref(""); // 详情标题栏
const painterList = ref([]); // 画师下拉框
const dialogOpen1 = ref(false); // 导出表格


const statusList = ref(goodsStutasEnums);
const useRangeList = ref([
  { label: "仅文游圈作者用", value: 1 },
  { label: "仅文游圈、小说、广播短剧作者用", value: 2 },
  { label: "全网可商用", value: 3 },
]);
const typeList = ref(goodsTypeEnums);
const openSub = ref(false); // 查看购买详情
const openPainter = ref(false); // 画师修改入口
const openShare = ref(false); // 打开分享
const dialogOpen2 = ref(false); // 导入表格
const dialogOpenPick = ref(false); // 导入表格 提货码

const fileList = ref([]);
const loadingBtn = ref(false);

const loadingSub = ref(false);
const pageListSub = ref([]);
const shareUrl = ref("");
const shareName = ref("");
const optionsPainterList = ref([]) // 存放画师
const loadingGoods = ref(false) // loading 


const data = reactive({
  stutasList: goodsStutasEnums,
  form: {},
  formPick: {},
  dialogForm1: {
    type: undefined,
    userId: undefined,
  }, // 导出弹出框选择
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    queryGoodsName: undefined,
    queryPainterName: undefined,
    orderType: undefined,
    orderName: undefined,
  },
  rules: {
    name: [{ required: true, message: "商品名称不能为空", trigger: "blur" }],
    userId: [{ required: true, message: "画师不能为空", trigger: "change" }],
    saleTime: [
      { required: true, message: "售卖日期不能为空", trigger: "change" },
    ],
  },
});

const { queryParams, form, formPick, rules, dialogForm1, stutasList } = toRefs(data);


/** 画师远程搜索 */
function remoteMethod2(query) {
  if (query) {
    loadingGoods.value = true;
    let queryParams = {
      pageNum: 1,
      pageSize: 50,
      queryNickname: query,
      type: 3
    };
    listUser(queryParams).then((response) => {
      optionsPainterList.value = response.data.rows.map((item) => {
        return {
          label: item.nickname,
          value: item.id,
        };
      });

      loadingGoods.value = false;
    });
  } else {
    optionsPainterList.value = [];
  }
}



const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== "image/png" && rawFile.type !== "image/jpeg") {
    // ElMessage.error("图片格式为必须为 PNG  !");
    proxy.$modal.msgError("图片格式为必须为 PNG  !");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 0.5) {
    // ElMessage.error("图片大小超过 500 kb!");
    proxy.$modal.msgError("图片大小超过 500 kb!");
    return false;
  }
  return true;
};
// 附件
const beforeFileUpload = (rawFile) => {
  if (rawFile.size / 1024 / 1024 > 2) {
    proxy.$modal.msgError("文件大于 2MB!");
    return false;
  }
  return true;
};
// 废弃
function onSuccessImg(response) {
  if (response.code == 200) {
    form.value.src = response.data;
    imageUrl.value = uploadShowUrl + response.data;
  }

  // getList();
}
// 批量提交成功后
function onSuccessFile(response) {
  if (response.code == 200) {
    proxy.$modal.msgSuccess(response.msg);
  } else {
    proxy.$modal.msgError(response.msg);
  }

  getList();
}
/** 查询画师列表 */
function getPainterList() {

  listAllUser().then((response) => {
    painterList.value = response.data.map((item) => {
      return {
        label: item.nickname || '-空-',
        value: item.id,
      };
    });
  });
}

/** 查询列表 */
function getList() {
  loading.value = true;
  listGoods(proxy.addDateRangeZL(queryParams.value, dateRange.value)).then((response) => {
    pageList.value = response.data.rows;
    total.value = response.data.count;
    loading.value = false;
  });
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  openPainter.value = false;
  openPick.value = false;
  reset();
}


/** 表单重置 */
function reset() {
  form.value = {
    name: undefined,
    userId: undefined,
    saleTime: undefined,
    price: 0,
    saleSum: 0,
    status: 1,
    useRange: 1,
    type: 1,
    src: "",
    useOtherPlatform: 1,
  };
  imageUrl.value = null;
  proxy.resetForm("noticeRef");
  formPick.value = {
    id: undefined,
    pick_up: undefined,
    remarks: undefined,

  };
  imageUrl.value = null;
  proxy.resetForm("goodsPickRef");
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  queryParams.value.orderType = undefined;
  queryParams.value.orderName = undefined;
  handleQuery();
}
/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}
/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "新增";
}
/**修改按钮操作 */
function handleUpdate(row) {
  reset();
  if (!row.id) {
    let arr = pageList.value.filter((item) => {
      return item.id == ids.value;
    });
    form.value = {
      ...arr[0]
    };
  } else {
    form.value = {
      ...row
    };
    imageUrl.value = uploadShowUrl + row.src;
  }

  open.value = true;
  title.value = "修改";
}
// 修改提货码
function handleUpdatePick(row) {
  reset();
  formPick.value = {
    id: row.id,
    pick_up: row.adminPickUp || undefined,
    remarks: row.adminRemarks || undefined,
  };

  openPick.value = true;
  title.value = "修改提货码";
}


// 防抖操作
const debouncedFnPick = useDebounceFn(
  () => {
    submitFormPick();
  },
  1000,
  { maxWait: 3000 }
);

// 防抖操作
const debouncedFn = useDebounceFn(
  () => {
    submitForm();
  },
  1000,
  { maxWait: 3000 }
);

/** 提交按钮 */
function submitForm() {
  proxy.$refs["noticeRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != undefined) {
        updateGoods(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          openPainter.value = false;
          getList();
        });
      } else {
        addGoods(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          openPainter.value = false;
          getList();
        });
      }
    }
  });
}

/** 提交按钮 */
function submitFormPick() {
  proxy.$refs["goodsPickRef"].validate((valid) => {
    if (valid) {

      updateGoodsPick(formPick.value).then((response) => {
        proxy.$modal.msgSuccess("修改成功");
        cancel();
        getList();
      });

    }
  });
}


/** 删除按钮操作 */
function handleDelete(row) {
  let deleteId = row.id || ids.value;
  if (!Array.isArray(deleteId)) {
    deleteId = [deleteId];
  }

  proxy.$modal
    .confirm('是否确认删除"' + row.name + '"的数据项？')
    .then(function () {
      return deleteGoods({ id: deleteId });
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => { });
}
/** 查看购买详情 */
function handleOpenSub(row) {
  openSub.value = true;
  loadingSub.value = true;
  listAllOrder({ goodsId: row.id }).then((response) => {
    let data = response.data.rows;

    pageListSub.value = data;
    detaiRemarks.value = row.remarks;


    detailTitle.value =
      "购买详情: " +
      row.name +
      " - " +
      row.nickName +
      " - " +
      response.data.rows.length +
      "份";
    detailTitle1.value = " - 总销售金额 " +
      response.data.allSalePrice +
      "元"
    loadingSub.value = false;
  });
}

function handleChangeUseRange(params) {
  let arr = useRangeList.value.filter((item) => {
    return item.value == params;
  });
  if (arr && arr.length > 0) {
    return arr[0].label;
  } else {
    return " ";
  }
}

function handleChangeType(params) {
  let arr = typeList.value.filter((item) => {
    return item.value == params;
  });
  if (arr && arr.length > 0) {
    return arr[0].label;
  } else {
    return " ";
  }
}
// 排序
function handleSortChange(column) {
  let data1;
  if (column.order == "ascending") {
    data1 = "ASC";
  } else if (column.order == "descending") {
    data1 = "DESC";
  }
  if (!data1) {
    data.queryParams.orderName = undefined;
  } else {
    data.queryParams.orderName = column.prop;
  }
  data.queryParams.orderType = data1;
  getList();
}
// 分享链接
function handleShare(row) {
  openShare.value = true;
  shareName.value = row.goodsName;
  shareUrl.value = `http://49.232.143.114/#/pages/subPackB/write/index?goods_id=${row.id}`;
  // shareUrl.value = `https://wuyanshusheng.cn/#/pages/subPackB/write/index?goods_id=${row.id}`;
}
function handleCopy() {
  // 获取需要复制的元素以及元素内的文本内容
  const container = document.getElementById("copy-text");
  const text = container.innerText;
  // 添加一个input元素放置需要的文本内容
  const copyContent = document.createElement("input");
  copyContent.value = text;
  document.body.appendChild(copyContent);
  // 选中并复制文本到剪切板
  copyContent.select();
  document.execCommand("copy");
  // 移除input元素
  document.body.removeChild(copyContent);
}
// 上传
async function handleFileUpload(event) {
  // let file =await parseFile(event.url)
  let file = event.file;
  const imageType = file.name.split(".")[1];
  let fileName = getRandomString(12, imageType);
  const currentDate = new Date(); // 创建一个表示当前时间的对象
  const year = currentDate.getFullYear(); // 获取年份
  const month = currentDate.getMonth() + 1; // 获取月份（注意需要加上1）
  const day = currentDate.getDate(); // 获取日期
  const nowDate = `${year}${month}${day}`;
  const fullPathKey = "goods/" + nowDate + fileName;

  const result = await h5UploadFile(file, fullPathKey);
  if (result.Location) {
    form.value.src = fullPathKey;
    imageUrl.value = uploadShowUrl + fullPathKey;
  } else {
    form.value.src = "";
    imageUrl.value = "";
  }
}

/** 导入表格 */
function handleUpload() {
  dialogReset2();
  dialogOpen2.value = true;
  title.value = "导入商品";
}

/** 导入提货码表格 */
function handleUploadPick() {
  dialogReset2();
  dialogOpenPick.value = true;
  title.value = "导入商品提货码";
}

/** 表单重置 */
function dialogReset2() {
  fileList.value = [];
}
/** 表单重置 */
function dialogReset1() {
  proxy.resetForm("orderRef1");
}
function handleExport() {
  dialogReset1();
  dialogOpen1.value = true;
  title.value = "导出表格";
}
/** 取消按钮 */
function dialogCancel1() {
  dialogOpen1.value = false;
  dialogReset1();
}
/** 下载标准模板 */
function submitUploadFileDemo(response) {
  let fileName = "商品批量上传标准模板2025.xlsx";
  loadingBtn.value = true;
  downExcelFile().then((response) => {
    loadingBtn.value = false;

    downFile(response, fileName);
  });
}

/** 下载标准模板  提货码 */
function submitUploadFileDemoPick(response) {
  let fileName = "商品提货码批量上传标准模板2025.xlsx";
  loadingBtn.value = true;
  goodsPickDownExcelFile().then((response) => {
    loadingBtn.value = false;

    downFile(response, fileName);
  });
}
// 可以将此方法封装
function downFile(content, filename) {
  // 创建隐藏的可下载链接
  var eleLink = document.createElement("a");
  eleLink.download = filename;
  eleLink.style.display = "none";
  // 字符内容转变成blob地址
  var blob = new Blob([content]);
  eleLink.href = URL.createObjectURL(blob);
  document.body.appendChild(eleLink);
  // 触发点击
  eleLink.click();
  // 然后移除
  document.body.removeChild(eleLink);
  proxy.$modal.msgSuccess("操作成功");
}

/** 取消按钮 */
function dialogCancel2() {
  dialogOpen2.value = false;
  dialogReset2();
}


/** 导出 */
function submitExport() {
  const dataForm = dialogForm1.value;
  let fileName = "商品列表" + ".xlsx";

  loadingBtn.value = true;
  downExcelGoods(dataForm).then((response) => {
    loadingBtn.value = false;

    downFile(response, fileName);
  });
}


getList();
getPainterList();
</script>
<style lang="scss" scoped>
.color-blue {
  color: rgb(0, 119, 255);
  cursor: pointer;
}

.avatar-uploader {
  width: 200px;
  height: 300px;

  .avatar {
    width: 100%;
    height: 100%;
  }
}

.avatar-uploader :deep(.el-upload) {
  width: 100%;
  height: 100%;
  border: 1px dashed #dcdfe6;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader :deep(.el-upload:hover) {
  border-color: #409eff;
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.pt {
  padding: 10px 0;
}

.detail-title {
  display: flex;
}
</style>
